package com.jackspace.service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.jackspace.bean.Request;
import com.jackspace.bean.RequestFacade;
import com.jackspace.bean.Response;
import com.jackspace.bean.ResponseFacade;
import com.jackspace.main.HttpServer;

public class ServletProcessor {
	
	public void process(Request request, Response response)
	{
		String uri = request.getUri();
		String servletName = uri.substring(uri.lastIndexOf("/") + 1);
		
		File file = new File(HttpServer.WEB_ROOT);
		URL[] urls = new URL[1];
		URLStreamHandler handler = null;
		try {
			String repository = new URL("file", null, file.getCanonicalPath() + File.separator).toString();			
			urls[0] = new URL(null, repository, handler);
			
			URLClassLoader loader = new URLClassLoader(urls);
			Class myClass = loader.loadClass(servletName);
			Servlet servlet = (Servlet)myClass.newInstance();
			//servlet.service((ServletRequest)request, (ServletResponse)response);
			RequestFacade requestFacade = new RequestFacade(request);
			ResponseFacade responseFacade = new ResponseFacade(response);
			servlet.service(requestFacade, responseFacade);
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
